import WebSocket from 'ws';
import logger from '../logger';

/**
 * 浏览器客户端对象。
 */
type onCloseCb = (bc: BroserClient) => void;
type onMessageCb = (bc: BroserClient, data: string) => void;
class BroserClient {
    private uuid: string = '';
    private socket: WebSocket;
    private onClose: onCloseCb;
    private onMessage: onMessageCb;
    private serviceId: number = -1;


    constructor(strUuid: string, socket: WebSocket) {
        this.uuid = strUuid;
        this.socket = socket;
        this.initSocket();
        this.onClose = (bc: BroserClient) => void {};
        this.onMessage = (bc: BroserClient, data: string) => void {};
    }
    private initSocket() {
        this.socket.on('message', (data: WebSocket.Data) => {
            this.onMessage(this, <string>data);
        });

        this.socket.on('close', (code: number, reason: string) => {
            this.onClose(this);
        });
    }


    setMessageCb(cb: onMessageCb): void {
        this.onMessage = cb;
    }
    setCloseCb(cb: onCloseCb) {
        this.onClose = cb;
    }

    getUuid(): string {
        return this.uuid;
    }
    setServiceId(sId: number) {
        this.serviceId = sId;
    }
    getServiceId(): number {
        return this.serviceId;
    }

    send(msg: string): boolean {
        this.socket.send(msg);
        return true;
    }
}

export = BroserClient;